# -*- coding: utf-8 -*-
#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import webapp

import time
import datetime
import urllib
import base64
from google.appengine.api import urlfetch
from google.appengine.ext import db

class SendChime(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		#username =  self.request.get("ru_kremlin")
		username =  "ru_kremlin"

		login =  username
		#ACHTUNG!
		password = ""
		
		class Hours(db.Model):
			date = db.DateProperty()
			hour = db.IntegerProperty()
			minutes = db.IntegerProperty()
		
		
		min = time.localtime(time.time()).tm_min
		hour = time.localtime(time.time()).tm_hour
		datetoday = datetime.date.today()
		if min == 0:
			chime = self.get_chime()
			payload= {'status' : chime,  'source' : "Bot"}
			payload= urllib.urlencode(payload)

			base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
			headers = {'Authorization': "Basic %s" % base64string} 

			url = "http://twitter.com/statuses/update.xml"
			result = urlfetch.fetch(url, payload=payload, method=urlfetch.POST, headers=headers)
			
			success = Hours(
						date = datetoday,
						hour = hour,
						minutes = min
						)
			success.put()
			
			#self.response.out.write(result.content)
			
		elif min > 0 and min < 4:
			q = db.GqlQuery("SELECT * FROM Hours WHERE date = :1 AND hour = :2" , datetoday, hour)
			result = q.fetch(1)
			if result:
				pass
			else:
				chime = self.get_chime()
				payload= {'status' : chime,  'source' : "Bot"}
				payload= urllib.urlencode(payload)

				base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
				headers = {'Authorization': "Basic %s" % base64string} 

				url = "http://twitter.com/statuses/update.xml"
				result = urlfetch.fetch(url, payload=payload, method=urlfetch.POST, headers=headers)
				
				success = Hours(
						date = datetoday,
						hour = hour,
						minutes = min
						)
				success.put()

				#self.response.out.write(result.content)
		else: 
			pass
			#left_min = 60 - min
			#message = 'Time not sharp. Wait ' + str(left_min) + ' minutes, please.'
			#self.response.out.write(message)
 
	def get_chime(self):
		# Old bad variant
		#now = time.localtime(time.time()).tm_hour
		#now += 3 # winter moscow time
		
		# winter moscow time
		delta = datetime.timedelta(hours=3)
		# summer moscow time
		#delta = datetime.timedelta(hours=4)
		
		nowgmt = datetime.datetime.today()
		nowmsk = nowgmt + delta
		
		tt = nowmsk.timetuple()
		now = tt.tm_hour
		
		if   now == 0:
			hour = ' часов'
		elif now == 1:
			hour = ' час. '
		elif now > 1 and now <5:
			hour = ' часа. '
		elif now > 4 and now <21:
			hour = ' часов. '
		elif now == 21:
			hour = ' час. '
		elif now > 21:
			hour = ' часа. '
		
		bom = 'Бом! ' 
		chime = 'В Москве ' + str(now) + hour + bom * now
		return chime


def main():
	application = webapp.WSGIApplication([('/', SendChime)],
                                       debug=True)
	wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
	main()
